<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .record {
        display: block;
        width: 50px;
        height: 50px;
        margin: 50px auto 0;
        background: url(./record.png) no-repeat;
        background-position: 0 0;
        background-size: 50px 100px;
        cursor: pointer;
        transition: 0.3s;
        overflow: hidden;
      }
      .record.active {
        background-position: 0 -50px;
      }
    </style>
  </head>
  <body>
    <span class="record"></span>
    <script>
      const oBtn = document.querySelector(".record");
      oBtn.addEventListener("click", async function () {
        this.classList.toggle("active");
        // Prompt user for authorization
        const stream = await navigator.mediaDevices.getDisplayMedia({
          audio: true,
          video: true,
        });
        // Check if the specified format can be recorded
        const mime = MediaRecorder.isTypeSupported("video/webm;codecs=vp9") ? "video/webm;codecs=vp9" : "video/webm";
        // Create recording object
        const mediaRecorder = new MediaRecorder(stream, {
          mimeType: mime,
        });
        const chunks = [];
        // Obtain recorded media resources
        mediaRecorder.addEventListener("dataavailable", function (e) {
          chunks.push(e.data);
        });
        // Stop recording
        mediaRecorder.addEventListener("stop", function () {
          const blob = new Blob(chunks, {
            type: chunks[0].type,
          });
          const url = URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.href = url;
          a.download = "video.webm";
          a.click();
        });
        mediaRecorder.start();
      });
    </script>
  </body>
</html>
